package com.example.demo.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demo.entity.Admin;
import com.example.demo.service.AdminService;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Component
public class JwtTokenUtils {

    private static AdminService staticAdminService; // 假设AdminService是你的服务类
    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtils.class);

    @Resource
    private AdminService adminService;

    @PostConstruct
    public void initAdminService() { // 修改方法名为initAdminService
        staticAdminService = adminService; // 确保这里的大小写与字段一致
    }
    public static String genToken(String UserId, String password) { // 修改参数名为signKey以表示它是一个密钥
        return JWT.create()
                .withAudience(UserId) // 将 user id 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(password));// 以signKey作为token的密钥
    }
    public static Admin getCurrentUser() {
        String token = null;
        try {
            // 获取HttpServletRequest
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            // 从header中获取token
            token = request.getHeader("token");
            // 如果header中没有，则从参数中获取
            if (StrUtil.isBlank(token)) {
                token = request.getParameter("token");
            }
            // 如果token为空，则记录日志并返回null
            if (StrUtil.isBlank(token)) {
                log.error("获取当前登录的token失败，token:{}", token);
                return null;
            }

            // 解析token，获取用户的id
            String adminId = JWT.decode(token).getAudience().get(0);// 假设token的audience中只有一个值
            // 转换为Integer并查找用户
           return staticAdminService.findById(Integer.valueOf(adminId));
            // 假设findById方法接受Integer类型的参数
        } catch (Exception e) {
            log.error("获取当前登录的管理员信息失败，token={}", token, e);
            return null;
        }
    }
}
